<script setup lang="ts">
import { ref, watch, PropType, onUnmounted } from 'vue';
import { storeToRefs } from 'pinia';
import { echarts } from './config';
import useThemeConfig from '@/stores/themeConfig';
import type { IECOption } from './type';

// 主题
const stores = useThemeConfig();
const { themeConfig } = storeToRefs(stores);

const props = defineProps({
	// 宽
	width: {
		type: String,
		default: () => '100%',
	},
	// 高
	height: {
		type: String,
		default: () => '100%',
	},
	// 是否开启 canvas 渲染器
	canvasRender: {
		type: Boolean,
		default: () => false,
	},
	// 配置项
	options: {
		type: Object as PropType<IECOption>,
		required: true,
	},
});

// echarts dom
const echartsRef = ref<HTMLElement>();
// echarts 实例
let mapChart: echarts.ECharts;

// 开始渲染echarts
const handleEcharts = () => {
	if (!echartsRef.value) throw new Error('echarts获取dom失败');
	// 如果实例存在 则删除
	mapChart && mapChart.dispose();
	/**
	 * 1. 初始化 echarts 实例
	 * light:浅色 dark: 深色
	 * renderer：数据量庞大 canvas 小 svg（性能快，缩放不会模糊）
	 */
	mapChart = echarts.init(echartsRef.value, themeConfig.value.isIsDark ? 'dark' : 'light', {
		renderer: props.canvasRender ? 'canvas' : 'svg',
	});
	// 2. 设置配置
	mapChart.setOption(props.options);
};

defineExpose({
	handleEcharts,
});
// 切换深夜模式
watch(
	() => themeConfig.value.isIsDark,
	() => {
		handleEcharts();
	}
);
// 屏幕发生变化 重新加载
window.onresize = () => mapChart && mapChart.resize();
// 组件销毁时 取消echarts实例
onUnmounted(() => {
	mapChart && mapChart.dispose();
});
</script>

<template>
	<div ref="echartsRef" class="echarts" :style="{ width: props.width, height: props.height }" />
</template>
